import axios from 'axios'
import * as qs from 'qs'
import store from '@/store'
import router from '@/router'

// import { Spin } from 'iview'
class HttpRequest {
	constructor(baseUrl = baseURL) {
		this.baseUrl = baseUrl
		this.queue = {}
	}
	getInsideConfig() {
		const config = {
			baseURL: this.baseUrl,
			headers: {
				//
			},
		}
		return config
	}
	distroy(url) {
		delete this.queue[url]
		if (!Object.keys(this.queue).length) {
			// Spin.hide()
		}
	}
	interceptors(instance, url) {
		// 请求拦截
		instance.interceptors.request.use(
			config => {
        config.data = qs.stringify(config.data)
				if (store.state.user.token !== undefined && store.state.user.token !== '') {
					config.headers['Authorization'] = store.state.user.token
				}
				config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
				this.queue[url] = true
				return config
			},
			error => {
				return Promise.reject(error)
			},
		)
		// 响应拦截
		instance.interceptors.response.use(
			res => {
				if (res.data.code == 401) {
					localStorage.setItem('user', "")
					router.push({
						name: 'login',
					})
				}
				this.distroy(url)
                const { data, status } = res
				return res.data
			},
			error => {
				this.distroy(url)
				return Promise.reject(error)
			},
		)
	}
	request(options) {
		const instance = axios.create()
		options = Object.assign(this.getInsideConfig(), options)
		this.interceptors(instance, options.url)
		return instance(options)
	}
}
export default HttpRequest
